<div class="text-container" style="width:{width}" data-uid="{uid}">
    {#if expandable}
    <textarea
        ref:textarea
        class:scroll
        bind:value
        on:input="resize(event.target)"
        style="height:{height}px"
        rows="1"
        {id}
        {disabled}
        {placeholder}
        {autocomplete}
    />
    {:else}
    <input type="text" bind:value {id} {disabled} {placeholder} {autocomplete} />
    {/if}
</div>

<style>
    .text-container {
        display: flex;
    }

    input,
    textarea {
        margin: 0 !important;
        width: 100%;
    }

    textarea {
        line-height: 20px !important;
        resize: none;
        overflow: hidden;
    }

    textarea.scroll {
        resize: vertical;
        overflow-y: scroll;
    }

    input[disabled],
    textarea[disabled] {
        cursor: default;
        color: #999;
    }
</style>

<script>
    const getScrollHeight = element => {
        const actualHeight = element.style.height; // Store original height of element
        element.style.height = 'auto'; // Set height to 'auto' in order to get actual scroll height
        const scrollHeight = element.scrollHeight - 8; // Deduct 8px to account for padding & borders
        element.style.height = actualHeight; // Reset to original height
        return scrollHeight;
    };

    export default {
        data() {
            return {
                value: '',
                id: '',
                uid: '',
                autocomplete: 'off',
                disabled: false,
                expandable: false,
                placeholder: '',
                width: '100%',
                height: 20,
                rows: 5
            };
        },

        methods: {
            resize(textarea) {
                const { lineHeight } = window.getComputedStyle(textarea);
                const maxHeight = parseInt(lineHeight) * this.get().rows;
                const newHeight = getScrollHeight(textarea);
                this.set({
                    height: maxHeight < newHeight ? maxHeight : newHeight,
                    scroll: maxHeight < newHeight
                });
            }
        },
        oncreate() {
            const { expandable } = this.get();
            if (expandable) this.resize(this.refs.textarea);
        }
    };
</script>
